/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.templet.web;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.persistence.Result;
import com.thinkgem.jeesite.common.utils.*;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.equipment.entity.EleEquipment;
import com.thinkgem.jeesite.modules.equipment.entity.EleEquipmentType;
import com.thinkgem.jeesite.modules.equipment.service.EleEquipmentService;
import com.thinkgem.jeesite.modules.publish.entity.EleSourceGroupPublish;
import com.thinkgem.jeesite.modules.publish.entity.EleTempletPublish;
import com.thinkgem.jeesite.modules.publish.service.EleTempletPublishService;
import com.thinkgem.jeesite.modules.source.dao.image.EleSourceImageDao;
import com.thinkgem.jeesite.modules.source.entity.EleSourceMultimedia;
import com.thinkgem.jeesite.modules.source.entity.alarm.EleSourceAlarm;
import com.thinkgem.jeesite.modules.source.entity.alarm.EleSourceAlarmGroup;
import com.thinkgem.jeesite.modules.source.entity.background.EleSourceBackground;
import com.thinkgem.jeesite.modules.source.entity.direction.EleSourceDirectionGroup;
import com.thinkgem.jeesite.modules.source.entity.floor.EleSourceFloor;
import com.thinkgem.jeesite.modules.source.entity.floor.EleSourceFloored;
import com.thinkgem.jeesite.modules.source.entity.floor.FloorNode;
import com.thinkgem.jeesite.modules.source.entity.font.EleSourceFont;
import com.thinkgem.jeesite.modules.source.entity.image.EleSourceImage;
import com.thinkgem.jeesite.modules.source.entity.logo.EleSourceLogo;
import com.thinkgem.jeesite.modules.source.entity.subtitle.EleSourceSubtitle;
import com.thinkgem.jeesite.modules.source.entity.subtitle.EleSourceSubtitleGroup;
import com.thinkgem.jeesite.modules.source.entity.time.EleSourceDate;
import com.thinkgem.jeesite.modules.source.entity.time.EleSourceTime;
import com.thinkgem.jeesite.modules.source.entity.title.EleSourceTitle;
import com.thinkgem.jeesite.modules.source.entity.video.EleSourceVideo;
import com.thinkgem.jeesite.modules.source.entity.weather.EleSourceWeather;
import com.thinkgem.jeesite.modules.source.entity.week.EleSourceWeek;
import com.thinkgem.jeesite.modules.source.service.EleSourceMultimediaService;
import com.thinkgem.jeesite.modules.source.service.alarm.EleSourceAlarmGroupService;
import com.thinkgem.jeesite.modules.source.service.direction.EleSourceDirectionGroupService;
import com.thinkgem.jeesite.modules.source.service.floor.EleSourceFloorService;
import com.thinkgem.jeesite.modules.source.service.floor.EleSourceFlooredService;
import com.thinkgem.jeesite.modules.source.service.floor.FloorNodeService;
import com.thinkgem.jeesite.modules.source.service.font.EleSourceFontService;
import com.thinkgem.jeesite.modules.source.service.logo.EleSourceLogoService;
import com.thinkgem.jeesite.modules.source.service.subtitle.EleSourceSubtitleGroupService;
import com.thinkgem.jeesite.modules.source.service.time.EleSourceDateService;
import com.thinkgem.jeesite.modules.source.service.time.EleSourceTimeService;
import com.thinkgem.jeesite.modules.source.service.title.EleSourceTitleService;
import com.thinkgem.jeesite.modules.source.service.video.EleSourceVideoService;
import com.thinkgem.jeesite.modules.source.service.weather.EleSourceWeatherService;
import com.thinkgem.jeesite.modules.source.service.week.EleSourceWeekService;
import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.Role;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.OfficeService;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.sys.utils.SwitchUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.templet.entity.EleTemplet;
import com.thinkgem.jeesite.modules.templet.entity.EleTempletSource;
import com.thinkgem.jeesite.modules.templet.service.EleTempletService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;

/**
 * 模板管理Controller
 * 
 * @author ZC
 * @version 2017-04-27
 */
@Controller
@RequestMapping(value = "${adminPath}/templet/eleTemplet")
public class EleTempletController extends BaseController {

	@Autowired
	private EleTempletService eleTempletService;
	@Autowired
	private EleEquipmentService eleEquipmentService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private EleTempletPublishService eleTempletPublishService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private EleSourceFontService eleSourceFontService;
	@Autowired
	private EleSourceVideoService videoService;
	@Autowired
	private EleSourceImageDao imageService;
	@Autowired
	private EleSourceWeatherService weatherService;
	@Autowired
	private EleSourceMultimediaService multimediaService;
	@Autowired
	private EleSourceSubtitleGroupService subService;
	@Autowired
	private EleSourceDateService dateService;
	@Autowired
	private EleSourceTimeService timeService;
	@Autowired
	private EleSourceWeekService weekService;
	@Autowired
	private EleSourceTitleService titleService;
	@Autowired
	private EleSourceFloorService floorService;
	@Autowired
	private FloorNodeService floorNodeService;
	@Autowired
	private EleSourceFlooredService flooredService;
	@Autowired
	private EleSourceDirectionGroupService directionService;
	@Autowired
	private EleSourceAlarmGroupService alarmService;
	@Autowired
	private EleSourceLogoService logoService;

	@ModelAttribute
	public EleTemplet get(@RequestParam(required = false) String id) {
		EleTemplet entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = eleTempletService.get(id);
		}
		if (entity == null) {
			entity = new EleTemplet();
		}
		return entity;
	}

	@RequiresPermissions("templet:eleTemplet:view")
	@RequestMapping(value = { "list", "" })
	public String list(EleTemplet eleTemplet, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		List<User> list = null;
		if (user.isAdmin()) {
			list = systemService.findAllUsers(user);
		} else {
			list = systemService.findAllUsersInCompany(user);
			list.add(UserUtils.getAdminUser());
		}
		eleTemplet.setUsers(list);

		Page<EleTemplet> page = eleTempletService.findPage(new Page<EleTemplet>(request, response), eleTemplet);
		Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);
		page.setLocale(locale);
		model.addAttribute("page", page);
		return "modules/templet/eleTempletList";
	}

	@RequiresPermissions("templet:eleTemplet:view")
	@RequestMapping(value = "form")
	public String form(EleTemplet eleTemplet,HttpServletRequest request, Model model) {
        if(eleTemplet != null){
            eleTemplet = mgrEleTemplet(eleTemplet);

			mgrHeightAndWidth(eleTemplet, model);
        }

		Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);
		model.addAttribute("language", locale.getLanguage());
		if(locale.getLanguage().equals(Locale.CHINESE.getLanguage())){
			model.addAttribute("langCode", locale.getLanguage()+"-cn");
		}else{
			model.addAttribute("langCode", locale.getLanguage());
		}

		model.addAttribute("eleTemplet", eleTemplet);
		model.addAttribute("eleTempletSource", new EleTempletSource());
		return "modules/templet/eleTempletForm";
	}

	@RequiresPermissions("templet:eleTemplet:edit")
	@RequestMapping(value = "importView")
	public String templateImportView(EleTemplet eleTemplet,HttpServletRequest request, Model model) {
		model.addAttribute("eleTemplet", eleTemplet);
		Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);  
		model.addAttribute("language", locale.getLanguage());
		if(locale.getLanguage().equals(Locale.CHINESE.getLanguage())){
			model.addAttribute("langCode", locale.getLanguage()+"-cn");
		}else{
			model.addAttribute("langCode", locale.getLanguage());
		}
		return "modules/templet/eleTempletImport";
	}

	@RequiresPermissions("templet:eleTemplet:edit")
	@RequestMapping(value = "import")
	public String templateImport(EleTemplet eleTemplet, Model model, RedirectAttributes redirectAttributes) {
		boolean importResult = true;
		try {

			EleTemplet tmp = eleTempletService.getbyTempleteByName(eleTemplet.getName());
			if (tmp != null) {
				String locale = I18nUtils.getLocaleStr();
				String msg = "模板名称已存在";
				if(Global.US.equals(locale)){
					msg = "The template name has already existed";
				}
				addMessage(redirectAttributes, msg);
				return "redirect:" + Global.getAdminPath() + "/templet/eleTemplet/importView";
			}
			importResult = eleTempletService.processImportTemplate(eleTemplet.getName(), eleTemplet.getUrl(), eleTemplet);
		} catch (IOException e) {
			e.printStackTrace();
			importResult = false;
			String basePath = Global.getUserfilesBaseDir();
			String fileBasePath = basePath.substring(0,basePath.lastIndexOf("\\elevator\\"))+"/";//basePath.replace("\\elevator\\","");
			String dirPath = fileBasePath+FileUtils.getFileNameWithoutExtension( eleTemplet.getUrl());
			FileUtils.deleteDirectory(dirPath);
			FileUtils.deleteFile(fileBasePath+eleTemplet.getUrl());
		}
		System.out.println(importResult);
		
		if (importResult) {
			String basePath = Global.getUserfilesBaseDir();
			EleTemplet tmp = eleTempletService.get(eleTemplet.getId());
			try {
				eleTempletService.createTemplateFile(tmp, basePath);
			} catch (Exception e) {
				logger.error(e.getMessage());
			}
			String locale = I18nUtils.getLocaleStr();
			String msg = "导入模板成功";
			if(Global.US.equals(locale)){
				msg = "Import template success";
			}
			addMessage(redirectAttributes, msg);
			/*addMessage(redirectAttributes, "导入模板成功");*/
		} else {
			String locale = I18nUtils.getLocaleStr();
			String msg = "导入模板失败";
			if(Global.US.equals(locale)){
				msg = "Import template fail";
			}
			addMessage(redirectAttributes, msg);
			/*addMessage(redirectAttributes, "导入模板失败");*/
		}
		return "redirect:" + Global.getAdminPath() + "/templet/eleTemplet/?repage";
	}

	@RequiresPermissions("templet:eleTemplet:edit")
	@RequestMapping(value = "save")
	public String save(EleTemplet eleTemplet, Model model, HttpServletRequest request) {

		if (!beanValidator(model, eleTemplet)) {
			return form(eleTemplet,request, model);
		}
		System.out.println(eleTemplet.getBackground() + "****************************************");
		eleTempletService.save(eleTemplet, null);

		// 生成代码
		/*
		 * if("0".equals(eleTemplet.getFlag())){ return "redirect:" +
		 * Global.getAdminPath() +
		 * "/templet/eleTemplet/form?id="+eleTemplet.getId(); } else{
		 */
		return "redirect:" + Global.getAdminPath() + "/templet/eleTemplet/show?id=" + eleTemplet.getId();
		/* } */
	}

	@RequiresPermissions("templet:eleTemplet:edit")
	@RequestMapping("selectSource")
	public String selectSource(EleTemplet eleTemplet, Model model) {
		eleTempletService.save(eleTemplet, null);

		// 生成代码
		if ("0".equals(eleTemplet.getFlag())) {
			return "redirect:" + Global.getAdminPath() + "/templet/eleTemplet/designTemplet?id=" + eleTemplet.getId();
		} else {
			return "redirect:" + Global.getAdminPath() + "/templet/eleTemplet/?repage";
		}
	}

	@RequiresPermissions("templet:eleTemplet:edit")
	@RequestMapping("designTemplet")
	public String designTemplet(EleTemplet eleTemplet, Model model) {
		model.addAttribute("eleTemplet", eleTemplet);
		return "modules/templet/designTempletForm";
	}

	@RequiresPermissions("templet:eleTemplet:edit")
	@RequestMapping("saveTempeteSource")
	@ResponseBody
	public Result saveTempeteSource(String eleTempletId, String name, String templateType, int width, int height, String remarks, String displaymode,
                                    String font, String fullscreen, String color, String bgImage, String bgGif, String eleTempletSourceList) {
        logger.info("saveTempeteSource, eleTempletSourceList={}", eleTempletSourceList);

		eleTempletSourceList = eleTempletSourceList.replace("&quot;", "\"");

		EleTemplet tmp = eleTempletService.getbyTempleteByName(name);
		if (tmp != null) {
			if (!tmp.getId().equals(eleTempletId)) {
				String locale = I18nUtils.getLocaleStr();
				String msg = "模板名称已存在";
				if(Global.US.equals(locale)){
					msg = "The template name has already existed";
				}
				return new Result(Result.FAILURE, msg, null);
			}
		}

		EleTemplet entity = new EleTemplet(eleTempletId);
		entity.setName(name);
		entity.setType(new EleEquipmentType(templateType));
        entity.setWidth(width);
        entity.setHeight(height);
		entity.setRemarks(remarks);
		entity.setDisplaymode(displaymode);
		entity.setFont(new EleSourceFont(font));
		entity.setFullscreen(fullscreen);
		EleSourceBackground back = new EleSourceBackground();
		back.setColor(color);
		back.setBgImage(bgImage);
		back.setBgGif(bgGif);
		entity.setBackground(back);
		User user = UserUtils.getUser();
		entity.setCheckBy(user);
		entity.setCheckDate(new Date());
		entity.setDelFlag("0");
		List<EleTempletSource> templetSourceList = new ArrayList<>();
		Map map = JsonMapper.getInstance().fromJson(eleTempletSourceList, Map.class);
		for (Object item : map.keySet()) {
			Map mapItem = (Map) map.get(item);

			EleTempletSource templetSource = JSONObject.parseObject(JSONObject.toJSONString(mapItem),
					EleTempletSource.class);

			String sourceType = templetSource.getSourceType();

			int itemWidth = parseInt(templetSource.getWidth());
			int itemHeight = parseInt(templetSource.getHeight());
			int itemXloc = parseInt(templetSource.getXloc());
			int itemYloc = parseInt(templetSource.getYloc());

			if (itemWidth < 0) {
				itemWidth = 0;
			}
			if (itemHeight < 0) {
				itemHeight = 0;
			}
			if (itemXloc < 0) {
				itemXloc = 0;
			}
			if (itemYloc < 0) {
				itemYloc = 0;
			}

			templetSource.setWidth(String.valueOf(itemWidth));
			templetSource.setHeight(String.valueOf(itemHeight));
			templetSource.setXloc(String.valueOf(itemXloc));
			templetSource.setYloc(String.valueOf(itemYloc));
			if ("multimedia".equals(sourceType) || "sub".equals(sourceType) || "title".equals(sourceType) || "floored".equals(sourceType)
			 || !StringUtils.isEmpty(templetSource.getResourceId())) {
				templetSourceList.add(templetSource);
			}
		}
		entity.setEleTempletSourceList(templetSourceList);
//		if (!UserUtils.getSubject().isPermitted("templet:eleTemplet:check")
//				&& !SwitchUtils.isClose("templet:eleTemplet:check")) {
//			entity.setCheckBy(UserUtils.getCheckUser(""));
//			entity.setDelFlag(EleEquipment.DEL_FLAG_AUDIT);
//		} else {
			entity.setCheckBy(UserUtils.getUser());
			entity.setDelFlag(EleEquipment.DEL_FLAG_NORMAL);
//		}
		eleTempletService.save(entity, "position");
		String basePath = Global.getUserfilesBaseDir();
		String msg = "";
		try {
			eleTempletService.createTemplateFile(entity, basePath);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			msg = "生成主题包失败!";
		}
		return new Result(Result.SUCCESS, msg, entity.getId());
	}

	private int parseInt(String value) {
		value = StringUtils.defaultIfEmpty(value, "0").replace("px", "");
		if (isNum(value)) {
			return Integer.parseInt(value);
		}
		return 0;
	}

	private boolean isNum(String str) {
		try {
			new BigDecimal(str);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 预览模板页面
	 * 
	 * @param eleTemplet
	 * @param model
	 * @return
	 */
	@RequiresPermissions("templet:eleTemplet:view")
	@RequestMapping(value = "show")
	public String show(EleTemplet eleTemplet, Model model) {
		eleTemplet = mgrEleTemplet(eleTemplet);

		mgrHeightAndWidth(eleTemplet, model);

		model.addAttribute("eleTemplet", eleTemplet);
		return "modules/templet/eleTempletShow";
	}

	private void mgrHeightAndWidth(EleTemplet eleTemplet, Model model){
		int width = eleTemplet.getWidth();
		int height = eleTemplet.getHeight();
		// 横屏
		int templetWidth = width;
		int templetHeight = height;
		if("0".equals(eleTemplet.getDisplaymode())){
			if(!(width >= height)){
				templetWidth = height;
				templetHeight = width;
			}
		}
		else{
			if(!(height >= width)){
				templetWidth = height;
				templetHeight = width;
			}
		}
		model.addAttribute("templetWidth", templetWidth);
		model.addAttribute("templetHeight", templetHeight);
	}

	private EleTemplet mgrEleTemplet(EleTemplet eleTemplet) {
		if (eleTemplet.getEleTempletSourceList() == null) {
			return eleTemplet;
		}
		// ====================================字典map=======================================
		Map<String, String> alignDictMap = new HashMap<>();
		List<Dict> dictList = DictUtils.getDictList("textalign");
		for (Dict dict : dictList) {
			alignDictMap.put(dict.getValue(), dict.getRemarks());
		}
		for (EleTempletSource source : eleTemplet.getEleTempletSourceList()) {
			if ("0".equals(source.getDelFlag())) {
				Map<String, Object> detail = new HashMap<>();

				String source_id = source.getResourceId();
				if ("date".equals(source.getSourceType())) {
					EleSourceDate item = dateService.get(source_id);
					detail.put("content", DateUtils.getDate(item.getFormat()));
					detail.put("color", item.getFgcolor());
					detail.put("bgcolor", item.getBgcolor());
					detail.put("size", item.getSize());

					detail.put("align", alignDictMap.get(item.getAlign()));

					detail.put("alpha", item.getAlpha());
					if (!"true".equals(item.getArea())) {
						detail.put("area", "display: none;");
					}
				} else if ("time".equals(source.getSourceType())) {
					EleSourceTime item = timeService.get(source_id);
					detail.put("content", DateUtils.getTimeByField(item.getFormat()));
					detail.put("color", item.getFgcolor());
					detail.put("bgcolor", item.getBgcolor());
					detail.put("size", item.getSize());

					detail.put("align", alignDictMap.get(item.getAlign()));

					detail.put("alpha", item.getAlpha());
					if (!"true".equals(item.getArea())) {
						detail.put("area", "display: none;");
					}
				} else if ("week".equals(source.getSourceType())) {
					EleSourceWeek item = weekService.get(source_id);
					detail.put("content", DateUtils.getWeekStr());
					detail.put("color", item.getFgcolor());
					detail.put("bgcolor", item.getBgcolor());
					detail.put("size", item.getSize());

					detail.put("align", alignDictMap.get(item.getAlign()));

					detail.put("alpha", item.getAlpha());
					if (!"true".equals(item.getArea())) {
						detail.put("area", "display: none;");
					}
				} else if ("title".equals(source.getSourceType())) {
					detail.put("type", "default");
					detail.put("content", "标题 Title");
					detail.put("color", "#FFFFFF");
					detail.put("size", "30");
					detail.put("align", "center");

					EleSourceTitle item = titleService.get(source_id);
					if (item != null) {
						detail.put("type", "title");
						detail.put("content", item.getContent());
						detail.put("color", item.getFgcolor());
						detail.put("bgcolor", item.getBgcolor());
						detail.put("size", item.getSize());

						detail.put("align", alignDictMap.get(item.getAlign()));

						detail.put("alpha", item.getAlpha());
						if (!"true".equals(item.getArea())) {
							detail.put("area", "display: none;");
						}
					}
				} else if ("sub".equals(source.getSourceType())) {
					detail.put("type", "default");
					detail.put("content", "字幕 Subtitle");
					detail.put("color", "#FFFFFF");
					detail.put("size", "30");
					detail.put("align", "center");

					EleSourceSubtitleGroup item = subService.get(source_id);
					if(item != null){
						List<EleSourceSubtitle> subtitles = item.getEleSourceSubtitleList();
						if(CollectionUtils.isNotEmpty(subtitles)){
							EleSourceSubtitle subtitle = subtitles.get(0);
							detail.put("type", "subtitle");
							detail.put("content", subtitle.getText());
							detail.put("color", item.getFgcolor());
							detail.put("bgcolor", item.getBgcolor());
							detail.put("size", item.getFontsize());

							detail.put("align", "center");

							detail.put("alpha", item.getAlpha());
							if(!"true".equals(item.getArea())){
								detail.put("area", "display: none;");
							}
						}
					}
				} else if ("weather".equals(source.getSourceType())) {
					EleSourceWeather item = weatherService.get(source_id);
					String locale = I18nUtils.getLocaleStr();
					if(Global.US.equals(locale)){
						detail.put("content", "Sunny");
					} else {
						detail.put("content", "晴天");
					}

					detail.put("color", item.getFgcolor());
					detail.put("bgcolor", item.getBgcolor());
					detail.put("size", item.getSize());

					detail.put("align", alignDictMap.get(item.getAlign()));

					detail.put("alpha", item.getAlpha());
				} else if ("logo".equals(source.getSourceType())) {
					EleSourceLogo item = logoService.get(source_id);
					detail.put("imgpath", item.getPath());
				} else if ("floor".equals(source.getSourceType())) {

					detail.put("type", "font");
                    detail.put("content", "FF");

					EleSourceFloor floor = floorService.get(source_id);
					if(null != floor){
						detail.put("align", alignDictMap.get(String.valueOf(floor.getAlignment())));

						String groupId = floor.getId();

						List<FloorNode> floorNodes = floorNodeService.getByGroupId(groupId);
						if(CollectionUtils.isNotEmpty(floorNodes)){
							FloorNode floorNode = floorNodes.get(0);
							detail.put("type", "image");
							detail.put("imgpath", floorNode.getFloorimg());
						}
					}
				} else if ("floored".equals(source.getSourceType())) {
                    EleSourceFloored floored = flooredService.get(source_id);
                    detail.put("column", floored.getColumn());
                    detail.put("width", floored.getColumnWidth());
                    detail.put("color", floored.getFgcolor());
                    detail.put("bgcolor", floored.getBgcolor());
                    detail.put("size", floored.getSize());
                    detail.put("align", alignDictMap.get(floored.getAlign()));
                    detail.put("w_space", floored.getHorizontalSpacing());
                    detail.put("lineheight", floored.getVerticalSpacing());
                }
                else if ("alarm".equals(source.getSourceType())) {
                    detail.put("content", "警告");
                    detail.put("type", "font");
					EleSourceAlarmGroup group = alarmService.get(source_id);
					if(null != group){
						List<EleSourceAlarm> alarms = group.getEleSourceAlarmList();
						if(CollectionUtils.isNotEmpty(alarms)){
							EleSourceAlarm alarm = alarms.get(0);
                            detail.put("type", "image");
							detail.put("imgpath", alarm.getImage());
						}
					}
				} else if ("direction".equals(source.getSourceType())) {
					EleSourceDirectionGroup directionGroup = directionService.get(source_id);
					String directionimg = "";
					String path = directionGroup.getUpstop();
					if(StringUtils.isNotEmpty(path)){
						path = path.replace("|", "");
						directionimg = path;
					}
					detail.put("imgpath", directionimg);
				} else if ("multimedia".equals(source.getSourceType())) {
                    detail.put("type", "default");

					EleSourceMultimedia multimedia = multimediaService.get(source_id);
                    if(multimedia != null){
                        if("image".equals(multimedia.getType())){
                            String groupId = multimedia.getImageId();
							List<EleSourceImage> images = imageService.getByGroupId(groupId);
                            detail.put("type", "image");
                            detail.put("imgpath", images.get(0).getPath());
                        }
                        else if("video".equals(multimedia.getType())){
                            String groupId = multimedia.getVideoId();
							List<EleSourceVideo> videos = videoService.getByGroupId(groupId);
                            detail.put("type", "video");
                            detail.put("imgpath", videos.get(0).getPath());
                        }
                    }
				}

				detail.put("area", "");

				source.setSourceDetail(detail);
			}
		}

		return eleTemplet;
	}

	/**
	 * 单独预览页面
	 * 
	 * @param sourceId
	 * @param sourceType
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "preview")
	public String preview(String sourceId, String sourceType, Model model) {
		Map<String, Object> source = new HashMap<>();

		// ====================================字典map=======================================
		Map<String, String> alignDictMap = new HashMap<>();
		List<Dict> dictList = DictUtils.getDictList("textalign");
		for (Dict dict : dictList) {
			alignDictMap.put(dict.getValue(), dict.getDescription());
		}

		if ("date".equals(sourceType)) {
			EleSourceDate date = dateService.get(sourceId);
			source.put("content", DateUtils.getDate(date.getFormat()));
			source.put("color", date.getFgcolor());
			source.put("bgcolor", date.getBgcolor());
			source.put("size", date.getSize());

			source.put("align", alignDictMap.get(date.getAlign()));

			source.put("alpha", date.getAlpha());
		} else if ("time".equals(sourceType)) {
			EleSourceTime time = timeService.get(sourceId);
			source.put("content", DateUtils.getTimeByField(time.getFormat()));
			source.put("color", time.getFgcolor());
			source.put("bgcolor", time.getBgcolor());
			source.put("size", time.getSize());

			source.put("align", alignDictMap.get(time.getAlign()));

			source.put("alpha", time.getAlpha());
		} else if ("week".equals(sourceType)) {
			EleSourceWeek week = weekService.get(sourceId);
			source.put("content", DateUtils.getWeekStr());
			source.put("color", week.getFgcolor());
			source.put("bgcolor", week.getBgcolor());
			source.put("size", week.getSize());

			source.put("align", alignDictMap.get(week.getAlign()));

			source.put("alpha", week.getAlpha());
		} else if ("title".equals(sourceType)) {
			EleSourceTitle title = titleService.get(sourceId);
			source.put("content", title.getContent());
			source.put("color", title.getFgcolor());
			source.put("bgcolor", title.getBgcolor());
			source.put("size", title.getSize());

			source.put("align", alignDictMap.get(title.getAlign()));

			source.put("alpha", title.getAlpha());
		} else if ("sub".equals(sourceType)) {
            EleSourceSubtitleGroup item = subService.get(sourceId);
            if(item != null){
                List<EleSourceSubtitle> subtitles = item.getEleSourceSubtitleList();
                if(CollectionUtils.isNotEmpty(subtitles)){
                    EleSourceSubtitle subtitle = subtitles.get(0);
                    source.put("content", subtitle.getText());
                    source.put("color", item.getFgcolor());
                    source.put("bgcolor", item.getBgcolor());
                    source.put("size", item.getFontsize());

                    source.put("align", "center");

                    source.put("alpha", item.getAlpha());
                }
            }
		} else if ("weather".equals(sourceType)) {
			EleSourceWeather weather = weatherService.get(sourceId);
			String locale = I18nUtils.getLocaleStr();
			if(Global.US.equals(locale)){
				source.put("content", "Sunny");
			} else {
				source.put("content", "晴天");
			}

			source.put("color", weather.getFgcolor());
			source.put("bgcolor", weather.getBgcolor());
			source.put("size", weather.getSize());

			source.put("align", alignDictMap.get(weather.getAlign()));

			source.put("alpha", weather.getAlpha());
		} else if ("logo".equals(sourceType)) {
			EleSourceLogo logo = logoService.get(sourceId);
			source.put("imgpath", logo.getPath());
		} else if ("floor".equals(sourceType)) {

            source.put("type", "font");
            source.put("content", "FF");

            EleSourceFloor floor = floorService.get(sourceId);
            if(null != floor){
                source.put("align", alignDictMap.get(String.valueOf(floor.getAlignment())));

                String groupId = floor.getId();

                List<FloorNode> floorNodes = floorNodeService.getByGroupId(groupId);
                if(CollectionUtils.isNotEmpty(floorNodes)){
                    FloorNode floorNode = floorNodes.get(0);
                    source.put("type", "image");
                    source.put("imgpath", floorNode.getFloorimg());
                }
            }
		} else if ("floored".equals(sourceType)) {
			EleSourceFloored floored = flooredService.get(sourceId);
            source.put("column", floored.getColumn());
            source.put("width", floored.getColumnWidth());
            source.put("color", floored.getFgcolor());
            source.put("bgcolor", floored.getBgcolor());
            source.put("size", floored.getSize());
            source.put("align", alignDictMap.get(floored.getAlign()));
            source.put("w_space", floored.getHorizontalSpacing());
            source.put("lineheight", floored.getVerticalSpacing());


		}else if ("alarm".equals(sourceType)) {
            source.put("content", "警告");
            source.put("type", "font");
            EleSourceAlarmGroup group = alarmService.get(sourceId);
            if(null != group){
                List<EleSourceAlarm> alarms = group.getEleSourceAlarmList();
                if(CollectionUtils.isNotEmpty(alarms)){
                    EleSourceAlarm alarm = alarms.get(0);
                    source.put("type", "image");
                    source.put("imgpath", alarm.getImage());
                }
            }
		}
		else if("direction".equals(sourceType)){
			EleSourceDirectionGroup directionGroup = directionService.get(sourceId);
			String directionimg = "";
			String path = directionGroup.getUpstop();
			if(StringUtils.isNotEmpty(path)){
				path = path.replace("|", "");
				directionimg = path;
			}
			source.put("imgpath", directionimg);
		}
		source.put("sourceType", sourceType);
		model.addAttribute("source", source);
		return "modules/source/eleFontSourceView";
	}

	@RequiresPermissions("templet:eleTemplet:view")
	@RequestMapping(value = "info")
	public String info(String publishId, Model model) {
		if (StringUtils.isNotEmpty(publishId)) {
			EleTempletPublish publish = eleTempletPublishService.get(publishId);
			model.addAttribute("publish", publish);
			EleTemplet eleTemplet = eleTempletService.get(publish.getTemplet().getId());
			model.addAttribute("eleTemplet", eleTemplet);
		}

		/* DateUtils.getDate(""); */

		return "modules/templet/eleTempletInfo";
	}

	@RequiresPermissions("templet:eleTemplet:view")
	@RequestMapping(value = "complete")
	public String complete(EleTemplet eleTemplet) {
		return "modules/templet/eleTempletComplete";
	}

	@RequiresPermissions("templet:eleTemplet:edit")
	@RequestMapping(value = "delete")
	public String delete(EleTemplet eleTemplet, RedirectAttributes redirectAttributes) {
		eleTempletService.delete(eleTemplet);
		String locale = I18nUtils.getLocaleStr();
		String msg = "删除模板成功";
		if(Global.US.equals(locale)){
			msg = "Templet deleted";
		}
		addMessage(redirectAttributes, msg);
		return "redirect:" + Global.getAdminPath() + "/templet/eleTemplet/?repage";
	}

	@RequiresPermissions("templet:eleTemplet:edit")
	@RequestMapping(value = "copy")
	public String copy(EleTemplet eleTemplet, HttpServletRequest request, Model model){
		List<EleTempletSource> sourceList = eleTemplet.getEleTempletSourceList();
		eleTemplet.setId("");
		eleTemplet.setName("");
		for (EleTempletSource source : sourceList) {
			source.setId("");
		}
		eleTemplet.setEleTempletSourceList(sourceList);
		// eleTempletService.save(eleTemplet,"copy");
		// System.out.println("===================================="+eleTemplet.getId());
		eleTemplet = mgrEleTemplet(eleTemplet);

		mgrHeightAndWidth(eleTemplet, model);

		model.addAttribute("eleTemplet", eleTemplet);
		model.addAttribute("eleTempletSource", new EleTempletSource());

		Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);
		model.addAttribute("language", locale.getLanguage());
		if(locale.getLanguage().equals(Locale.CHINESE.getLanguage())){
			model.addAttribute("langCode", locale.getLanguage()+"-cn");
		}else{
			model.addAttribute("langCode", locale.getLanguage());
		}

		return "modules/templet/eleTempletForm";
	}

	@RequiresPermissions("templet:eleTemplet:publish")
	@RequestMapping(value = "applypublish")
	public String applypublish(EleTemplet eleTemplet, EleEquipment eleEquipment,  RedirectAttributes redirectAttributes, Model model,
							   HttpServletRequest request) {
		// Edited by jyz (2018.5)
		String basePath = Global.getUserfilesBaseDir();
		EleTemplet entity = eleTempletService.get(eleTemplet.getId());
		try {
			eleTempletService.createTemplateFile(entity, basePath);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		String zipPath = basePath + "/theme/source/"+eleTemplet.getId()+"/" + eleTemplet.getId() + ".zip";
		File zipFile = new File(zipPath);
		if(!zipFile.exists()) {
			String locale = I18nUtils.getLocaleStr();
			String msg = "该资源对应文件不存在，请重新编辑保存后再尝试";
			if(Global.US.equals(locale)){
				msg = "The resource corresponding file does not exist, please re-edit it and try again";
			}
			addMessage(redirectAttributes, msg);
			return "redirect:"+ request.getHeader("referer");
		}

		List<Office> listTree = new ArrayList<>();

		User current = UserUtils.getUser();

		List<User> resultList = getBranchForUser(current);
		Set<String> ids = new HashSet<String>();
		for (User temuser : resultList) {
			String officeId = temuser.getOffice().getId();
			String companyId = temuser.getCompany().getId();
			ids.add(officeId);
			ids.add(companyId);
		}
		List<Office> listOffice = officeService.findList(true);

		Set<String> officeIds = new HashSet<>();
		Set<String> eqIds = new HashSet<>();
		for (User tmp : resultList) {
			EleEquipment eleEquipmentTmp = new EleEquipment();
			eleEquipmentTmp.setCompany(tmp.getCompany());
			eleEquipmentTmp.setOffice(tmp.getOffice());

			List<EleEquipment> listEquipment = eleEquipmentService.findList(eleEquipmentTmp);
			for (EleEquipment equipment : listEquipment) {
				officeIds.add(equipment.getCompany().getId());
				officeIds.add(equipment.getOffice().getId());
				if (eqIds.contains(equipment.getId())) {
					continue;
				}
				eqIds.add(equipment.getId());
				Office Office = new Office();
				Office.setId(equipment.getId());
				Office.setParent(new Office(equipment.getOffice().getId()));
				Office.setAddress(equipment.getCode());
				Office.setEmail(equipment.getType().getName());
				Office.setFax(equipment.getWidth() + " X " + equipment.getHeight());
				Office.setRemarks(equipment.getRemarks());
				if ("1".equals(equipment.getState())) {
					Office.setGrade("在线");
				} else {
					Office.setGrade("离线");
				}
				Office.setPhone("");
				Office.setZipCode(equipment.getName());

				listTree.add(Office);
			}
		}
		Set<String> resultSet = new HashSet<String>();
		for (String oid : officeIds) {
			resultSet.add(oid);
			Office tmp = officeService.get(oid);
			for (int i = 0; i < listOffice.size(); i++) {
				Office item = listOffice.get(i);
				if (item.getId().equals(tmp.getParentId())) {
					System.out.println(item);
					tmp = item;
					i = -1;
					resultSet.add(item.getId());
				}
			}
		}
		for (String oid : resultSet) {
			Office item = officeService.get(oid);
			item.setAddress(null);
			item.setEmail(null);
			item.setFax(null);
			item.setRemarks(null);
			item.setGrade(null);
			item.setPhone("display:none;");
			item.setZipCode("");

			listTree.add(item);
		}
		model.addAttribute("list", listTree);
		model.addAttribute("user", current);
		model.addAttribute("eleEquipment", eleEquipment);
		model.addAttribute("eleTemplet", eleTemplet);

		return "modules/templet/eleTempletPublish";
	}

	private List<User> getBranchForUser(User current) {
		User user = new User();
		List<User> list = systemService.findList(user);
		Role role = current.getRole();
		List<User> resultList = new ArrayList<User>();
		if (current.getUserType().equals("1")) {
			resultList = list;
		} else if (current.getUserType().equals("4")) {
			resultList.add(current);
		} else if (current.getUserType().equals("3")) {
			for (User usr : list) {
				if (usr.getUserType().equals("4")
						&& usr.getCompany().getId().equals(current.getOffice().getId())) {
					resultList.add(usr);
				}
			}
			resultList.add(current);
		} else {
			Set<String> offices = new HashSet<String>();
			for (User usr : list) {
				if (usr.getUserType().equals("3")
						&& usr.getCompany().getId().equals(current.getOffice().getId())) {
					resultList.add(usr);
					offices.add(usr.getOffice().getId());
				}
			}
			offices.add(current.getOffice().getId());
			for (User usr : list) {
				if (usr.getUserType().equals("4") && offices.contains(usr.getCompany().getId())) {
					resultList.add(usr);
				}
			}
			resultList.add(current);
		}
		return resultList;
	}

	@RequiresPermissions("templet:eleTemplet:publish")
	@RequestMapping(value = "publish")
	@ResponseBody
	public Result publish(String equipmentLists, String egId) {
		User thisuser = UserUtils.getUser();
		String[] ems = equipmentLists.split(",");
		boolean noNeedCheck = UserUtils.getSubject().isPermitted("templet:eleTemplet:check")
				|| SwitchUtils.isClose("templet:eleTemplet:check");
		System.out.println(egId);
		// 设置 申请 批次
		String publishBatch = IdGen.uuid();
		List<EleTempletPublish> publishList = new ArrayList<>();
		for (String emId : ems) {
			if (StringUtils.isNotBlank(emId)) {
				EleTempletPublish esgp = new EleTempletPublish();
				esgp.setPublishBatch(publishBatch);
				esgp.setEquipment(new EleEquipment(emId));
				esgp.setTemplet(new EleTemplet(egId));

				if (noNeedCheck) {
					esgp.setCheckDate(new Date(System.currentTimeMillis()));
					esgp.setCheckBy(thisuser);
					esgp.setDelFlag(EleSourceGroupPublish.DEL_FLAG_NORMAL);
				} else {
					esgp.setCheckBy(UserUtils.getCheckUser(""));
					esgp.setDelFlag(EleSourceGroupPublish.DEL_FLAG_AUDIT);
				}
				publishList.add(esgp);
			}
		}
		eleTempletPublishService.batchInsertTemplet(publishList);

		return new Result(Result.SUCCESS, noNeedCheck ? "发布成功!" : "提交发布申请,等待管理员审核!", null);
	}

	@RequiresPermissions("templet:eleTemplet:edit")
	@RequestMapping("applylist")
	public String applylist(EleTempletPublish eleTemplet, String isFirst, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		User thisUser = UserUtils.getUser();
		eleTemplet.setCreateBy(thisUser);
		if (StringUtils.isEmpty(isFirst)) {
			eleTemplet.setDelFlag(User.DEL_FLAG_AUDIT);
		}
		Page<EleTempletPublish> page = eleTempletPublishService
				.findPublishPage(new Page<EleTempletPublish>(request, response), eleTemplet);
		Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);
		page.setLocale(locale);
		model.addAttribute("page", page);
		model.addAttribute("isFirst", "no");

		return "modules/templet/myEleTempletList";
	}

	/**
	 * 审核记录
	 * 
	 * @param eleTemplet
	 * @param isFirst
	 * @param flag
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("templet:eleTemplet:check")
	@RequestMapping("mychecklist")
	public String checklist(EleTempletPublish eleTemplet, String isFirst, boolean flag, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		User thisUser = UserUtils.getUser();

		if (StringUtils.isEmpty(isFirst)) {
			eleTemplet.setDelFlag(User.DEL_FLAG_AUDIT);
		}
		List<User> branches = this.getSubListForUserForCheck(thisUser);
		Page<EleTempletPublish> page = new Page<>();
		if (!branches.isEmpty()) {
			page = eleTempletPublishService.findPublishPageForCheck(eleTemplet, new Page<EleTempletPublish>(request, response),
					branches, eleTemplet.getDelFlag());
		}
		Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);
		page.setLocale(locale);
		model.addAttribute("page", page);
		model.addAttribute("flag", flag);
		model.addAttribute("isFirst", "no");

		return "modules/templet/myEleTempletCheckList";
	}

	@RequiresPermissions("templet:eleTemplet:check")
	@RequestMapping(value = "check")
	public String check(String publishId, String delFlag, RedirectAttributes redirectAttributes) {
		EleTempletPublish publish = new EleTempletPublish(publishId);
		Result result;
		if ("1".equals(delFlag)) {
			result = eleTempletPublishService.delApprovalPublish(publish);
		} else {
			publish.setDelFlag(delFlag);

			publish.setCheckDate(new Date());
			publish.setCheckBy(UserUtils.getUser());
			result = eleTempletPublishService.checkPublish(publish);
		}
		addMessage(redirectAttributes, result.getMsg());
		return "redirect:" + adminPath + "/templet/eleTemplet/info?publishId=" + publishId;
	}

	@RequiresPermissions("templet:eleTemplet:view")
	@RequestMapping("resubmit")
	@ResponseBody
	public Result resubmitTemplete(String templetList) {
		String templets = templetList.substring(0, templetList.length() - 1);

		System.out.println(templets);

		String status = EleTempletPublish.DEL_FLAG_AUDIT;
		String msg = "已重新提交审核";
		User thisuser = UserUtils.getUser();
		eleTempletPublishService.bathcUpdateTempletStatus(templets, status, thisuser.getId(), "");

		return new Result(Result.SUCCESS, msg, null);
	}

	@RequiresPermissions("equipment:eleEquipment:check")
	@RequestMapping("checkList")
	@ResponseBody
	public Result checkList(String templetList, String flag, String type, String comment) {
		String templets = templetList.substring(0, templetList.length() - 1);

		System.out.println(templets);

		String status;
		String msg;
		if ("delete".equals(flag)) {
			status = EleEquipment.DEL_FLAG_DELETE;
			String locale = I18nUtils.getLocaleStr();
			msg = "删除成功";
			if(Global.US.equals(locale)){
				msg = "Deleted";
			}
			if ("approval".equals(type)) {
				eleTempletPublishService.delApprovalTempletStatus(templets, status);
			} else {
				eleTempletPublishService.delApplyTempletStatus(templets, status);
			}

			return new Result(Result.SUCCESS, msg, null);
		}

		User thisuser = UserUtils.getUser();
		if ("reject".equals(flag)) {
			status = EleEquipment.DEL_FLAG_AUDIT_NO;
			String locale = I18nUtils.getLocaleStr();
			msg = "未通过审核";
			if(Global.US.equals(locale)){
				msg = "Not passed";
			}

		} else {
			status = EleEquipment.DEL_FLAG_NORMAL;
			String locale = I18nUtils.getLocaleStr();
			msg = "审核通过";
			if(Global.US.equals(locale)){
				msg = "passed";
			}
		}
		eleTempletPublishService.bathcUpdateTempletStatus(templets, status, thisuser.getId(), comment);
		return new Result(Result.SUCCESS, msg, null);
	}

	@RequiresPermissions("equipment:eleEquipment:edit")
	@RequestMapping(value = "download")
	public String download(EleTemplet eleTemplet, HttpServletResponse response,
						   HttpServletRequest request, RedirectAttributes redirectAttributes) {
		String basePath = Global.getUserfilesBaseDir();
		EleTemplet entity = eleTempletService.get(eleTemplet.getId());
		try {
			eleTempletService.createTemplateFile(entity, basePath);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		String zipPath = basePath + "/theme/source/" + eleTemplet.getId() + "/";
		String zipName = eleTemplet.getId() + ".zip";
		File zipFile = new File(zipPath + zipName);
		if(!zipFile.exists()) {
			String locale = I18nUtils.getLocaleStr();
			String msg = "该资源对应文件不存在，请重新编辑保存后再尝试";
			if(Global.US.equals(locale)){
				msg = "The resource corresponding file does not exist, please re-edit it and try again";
			}
			addMessage(redirectAttributes, msg);
			return "redirect:"+ request.getHeader("referer");
		}

		downloadFile(zipPath, zipName, response);
		return "redirect:"+ request.getHeader("referer");
	}

	public void downloadFile(String filePath, String fileName, HttpServletResponse response) {
		response.setCharacterEncoding("utf-8");
		// response.setContentType("application/octet-stream");

		try {
			File file = new File(filePath, fileName);
			// 以流的形式下载文件。
			BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			// 清空response
			response.reset();
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			toClient.write(buffer);
			toClient.flush();
			toClient.close();

		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	@RequiresUser
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> list(EleTemplet eleTemplet, HttpServletResponse response) {
		response.setContentType("application/json; charset=UTF-8");
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<EleTemplet> list = eleTempletService.findList(eleTemplet);
		for (EleTemplet e : list) {
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", e.getId());
			map.put("pId", 0);
			map.put("name", e.getName());
			mapList.add(map);
		}
		return mapList;
	}

	public List<User> getSubListForUserForCheck(User current) {
		User user = new User();
		user.setDelFlag(null);
		List<User> list = systemService.findList(user);
		Role role = current.getRole();
		List<User> resultList = new ArrayList<User>();
		if (current.getUserType().equals("1")) {
			for (User usr : list) {
				resultList.add(usr);
			}
		} else if (current.getUserType().equals("4")) {
			// resultList.add(current);
		} else if (current.getUserType().equals("3")) {
			for (User usr : list) {
				if (usr.getUserType().equals("4")
						&& usr.getCompany().getId().equals(current.getCompany().getId())
						&& usr.getOffice().getId().equals(current.getOffice().getId())) {
					resultList.add(usr);
				}
			}
			// resultList.add(current);
		} else {
			Set<String> offices = new HashSet<String>();
			for (User usr : list) {
				if (usr.getUserType().equals("3")
						&& usr.getCompany().getId().equals(current.getOffice().getId())) {
					resultList.add(usr);
					offices.add(usr.getOffice().getId());
				}
			}
			for (User usr : list) {
				if (usr.getUserType().equals("4") && offices.contains(usr.getCompany().getId())) {
					resultList.add(usr);
				}
			}
			offices.add(current.getOffice().getId());
			// resultList.add(current);
		}
		for (User temuser : resultList) {
			temuser.setRemarks(User.DEL_FLAG_NORMAL.equals(temuser.getDelFlag()) ? "正常" : "审核中");
		}
		return resultList;
	}
}